package te.jetty.http;

import java.io.IOException;
import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.FilterMapping;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import com.sun.jersey.spi.container.servlet.ServletContainer;

import te.jetty.http.rest.CorsHandler;
import te.jetty.http.rest.Filter1;
import te.jetty.http.rest.Filter2;
import te.jetty.http.rest.MyServlet;
import te.jetty.http.rest.hellohandle;

public class demo {
	/**
	 * 测试用的main函数.
	 */
	public static void main(String[] args) throws Exception {
		int port = 8282;

		Server server = new Server(); // 监听8282端口
		ServerConnector connector = new ServerConnector(server);
		connector.setPort(port);
		server.addConnector(connector);

		// ServletContextHandler context = new
		// ServletContextHandler(ServletContextHandler.SESSIONS);
		ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
		context.setContextPath("/");
		context.addServlet(全局句柄(), "/*"); // 并行处理
		context.addServlet(new ServletHolder(new MyServlet()), "/h");
		context.addFilter(Filter1.class, "/*", EnumSet.of(DispatcherType.REQUEST));// 串行处理
		context.addFilter(Filter2.class, "/*", EnumSet.of(DispatcherType.REQUEST));

		CorsHandler corsHandler = new CorsHandler();// 跨域处理
		HandlerCollection hc = new HandlerCollection();
		hc.setHandlers(new Handler[] { corsHandler, context }); // 如果有多个handle 在这里添加

		server.setHandler(hc);
		// context.setHandler(单个句柄());//两次setHandler只有后面这次有用
		server.start();
		System.out.println("开启...端口= " + port);
	}

	public static ServletHolder 全局句柄() {
		ServletHolder servlet = new ServletHolder(ServletContainer.class);
		// 设置初始化参数
		servlet.setInitParameter("com.sun.jersey.config.property.resourceConfigClass",
				"com.sun.jersey.api.core.PackagesResourceConfig");
		servlet.setInitParameter("com.sun.jersey.config.property.packages", "te.sc.sso.rest");
		servlet.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true"); // 自动将对象映射成json返回

		return servlet;
	}

	public static ServletHandler 带参数实例化过滤器() {

		// 如果过滤器需要用参数实例化
		ServletHandler handler = new ServletHandler();
		handler.addFilterWithMapping(Filter2.class, "/*", EnumSet.of(DispatcherType.REQUEST));
		FilterHolder fh = handler.addFilterWithMapping(Filter1.class, "/*", EnumSet.of(DispatcherType.REQUEST));
		fh.setInitParameter("initParamKey", "初始化");
		return handler;
	}

	public static ContextHandler 单个句柄() {
		// Add a single handler on context "/hello"
		ContextHandler context = new ContextHandler();
		context.setContextPath("/hello");
		context.setHandler(new hellohandle()); // 一定要设置调用的类
		return context;
	}

	// HandlerWrapper用法
	public static HandlerList testlist1() {
		// create the handlers

		HandlerWrapper wrapper = new HandlerWrapper() {
			@Override
			public void handle(String target, Request baseRequest, HttpServletRequest request,
					HttpServletResponse response) throws IOException, ServletException {
				request.setAttribute("welcome", "Wylazy");
				super.handle(target, baseRequest, request, response);
			}
		};

		hellohandle hello = new hellohandle();
		wrapper.setHandler(hello);

		Handler param = new CorsHandler();

		Handler dft = new DefaultHandler();
		HandlerList list = new HandlerList();

		list.setHandlers(new Handler[] { param, wrapper, dft });
		return list;
	}

	/// HandlerList会依次调用每一个Handler，直到某个Handler将请求标记为已处理，即setHandled(true);
	// HandlerList顺序执行handler,如果抛出错误才执行下一个handler,否则不执行。如：
	public static HandlerList testlist2() {
		ResourceHandler resource_handler = new ResourceHandler();
		resource_handler.setDirectoriesListed(true);
		resource_handler.setWelcomeFiles(new String[] { "index.html" });

		resource_handler.setResourceBase(".");

		HandlerList handlers = new HandlerList();
		handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
		return handlers;
	}

	// //HandlerCollection会依次调用每一个Handler，即使请求已经被处理了
	// HandlerCollection会按照顺序分别执行每个handler，并把结果拼凑到response，返回。如下：
	public static HandlerCollection testColl() {
		HandlerCollection hc = new HandlerCollection();
		hc.setHandlers(new Handler[] { new hellohandle(), new DefaultHandler() });
		return hc;
	}
}
